#1
import pandas as pd
#定义数据集的列名
file = 'item4/wine.data'
names=['label','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13']
dataset=pd.read_csv(file,names=names)

print('葡萄酒数据集如下：')
print(dataset)

#分别提取特征和标签值数组
data =dataset.iloc[range(0,178),range(1,14)]
target=dataset.iloc[range(0,178),range(0,1)]
print(f'特征数组的形状：{data.shape}')
print(f"特征数组的形状：{target.shape}")


#2
import matplotlib.pyplot as plt

#画箱型图
#plt.style.use('seaborn-darkgrid')
plt.rcParams['axes.unicode_minus']=False		#正常显示负号
data.plot(kind='box',subplots=True,layout=(3,5),sharex=False,sharey=False)

#查找异常数据并输出
p=data.boxplot(return_type='dict')	             #返回字典类型数据
for i in range(13):
    y=p['fliers'][i].get_ydata()			#查找异常数据
    print('a',i+1,'中异常值：',y)			#输出异常数据
plt.show()


#3
import pandas as pd

file = 'item4/wine-clean.data'
names=['label','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13']
dataset=pd.read_csv(file,names=names)

#数据切片
data =dataset.iloc[range(0,178),range(1,14)]
target =dataset.iloc[range(0,178),range(0,1)].values.reshape(1,178)[0]
print(f'特征数组的形状：{data.shape}')
print(f"特征数组的形状：{target.shape}")


from sklearn import preprocessing
cdata=preprocessing.StandardScaler().fit_transform(data)
print(cdata)


#4查找最优k值
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier 
from sklearn.model_selection import train_test_split 
from sklearn.model_selection import cross_val_score	
x,y=cdata,target
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0) 

#定义k值选值范围
k_range=range(1,15)	
k_error=[]	
for k in k_range:
   model=KNeighborsClassifier(n_neighbors=k)
   scores=cross_val_score(model,x,y,cv=5,scoring='accuracy')
   k_error.append(1-scores.mean())


#绘制图版得到最优的k值
plt.rcParams['font.sans-serif']='Simhei'
plt.plot(k_range,k_error,'r-')
plt.xlabel('k的取值')
plt.ylabel('预测误差率')
plt.show()
  


#5使用k值等于9来进行训练模型并评估
from sklearn.metrics import accuracy_score

model=KNeighborsClassifier(n_neighbors=9)
model.fit(x_train,y_train)
pred=model.predict(x_train,y_train)


print (f'测试集的预测标签：{pred}')
print(f'测试集的真实标签：{y_test}')

ac =  accuracy_score(y_test,pred)
print(f'模型预测准确率：{ac}')